import {Injectable} from "@angular/core";
import {Events, Platform} from "ionic-angular";
import {AppGlobal, AppService} from "./app.service";
import {UserInfoService} from "./userInfo.service";
import {JPush} from "@jiguang-ionic/jpush";
import {FileTransfer, FileTransferObject} from "@ionic-native/file-transfer";
import {File} from "@ionic-native/file";
import {MessageService} from "./message.service";
import {Storage} from "@ionic/storage";
import {AppVersion} from "@ionic-native/app-version";
import {AppConfig} from "../../app/app.config"
import {SysDictService} from "./sysDict.service";
import {OrgService} from "./org.service";
import {ResDataModel} from "../models/res-data-model";
import {Device} from "@ionic-native/device";
import { normalizeURL } from 'ionic-angular';
import {SqliteService} from "./sqlite.service";

@Injectable()
export class AppInitService {
  constructor(private platform: Platform,
              private appService:AppService,
              private appVersion: AppVersion,
              private userInfoService:UserInfoService,
              private messageService:MessageService,
              private sysDictService:SysDictService,
              private sqliteService:SqliteService,
              private orgService:OrgService,
              private device:Device,
              private jPush:JPush,
              private file:File,
              private storage:Storage,
              private transfer:FileTransfer,
              private events:Events){

  }

  //初始化
  init(){
    this.storage.get("Inited").then(value => {
      if(value!=null){//不为空，说明不是第一次初始化
      } else {//为空，说明是第一次初始化
        this.storage.set("Inited",true);
      }
    })
    //
    this.sqliteService.init().then(()=>{
        //本地SQLite建表（消息）
        this.messageService.creatMsgTable();
        //本地SQLite建表（字典）
        this.sysDictService.createSysDictTable();
        //本地SQLite建表（机构）
        this.orgService.createOrgTable();
        //同步字典信息
        this.sysDictService.sysnDicts();
    })

    //平台判断
    if(this.platform.is('cordova')) {//native
      //指定请求api
      this.appService.domain = AppConfig.NativeApi;

      this.storage.get('device').then((value)=>{
        if(!value) {//不存在设备信息
          //构建device的json对象
          let deviceObject = {
            uuid:this.device.uuid,
            serial:this.device.serial,
            platform:this.device.platform,
            version:this.device.version,
            model:this.device.model,
            manufacturer:this.device.manufacturer,
            cordova:this.device.cordova,
            isVirtual:this.device.isVirtual
          };
          //缓存设备信息
          this.storage.set('device',deviceObject);
        }
      })

      /*储存版本信息*/
      this.appVersion.getVersionNumber().then(data => {
        //当前app版本号  data，存储该版本号
        AppGlobal.appVersion = data;
        console.log("获取版本号:"+data);
      }, error => {
        //获取当前版本号失败进行的操作
        console.error("获取版本号失败：" + error);
      });

      this.appVersion.getPackageName().then(data => {
        //当前应用的packageName：data，存储该包名
        AppGlobal.packageName = data;
        console.log("获取packageName:"+data);
      }, error => {
        //获取该APP id 失败
        console.error("获取packageName败：" + error);
      });

      //存储路径
      AppGlobal.platform = this.device.platform;
      AppGlobal.savePath = AppGlobal.platform == 'iOS' ?
          this.file.documentsDirectory : this.file.externalDataDirectory;
      AppGlobal.cachePath = this.file.cacheDirectory;
     // console.log(this.file);

      //alert("储存路径:"+normalizeURL(this.file.documentsDirectory));
      //alert("dataDirectory:"+file.dataDirectory+" cacheDirectory:"+file.cacheDirectory);

      //初始化极光服务
      //alert("开始注册极光推送！");
      this.jPush.init().then(res => { alert("初始化："+JSON.stringify(res)) },(err:any) => {
        alert("init err:"+JSON.stringify(err));
      })
        .catch((err:any)=>{
          alert("init err:"+JSON.stringify(err));
        });

      /*极光推送配置*/
      //注册极光服务监听
      document.addEventListener('jpush.receiveRegistrationId', (event:any) => {
        alert("registrationId:"+JSON.stringify(event));
        //alert("极光推送注册成功！RegistrationId为:"+event.registrationId);
        AppGlobal.jPushInited = true;
      }, false);

      //打开通知监听
      document.addEventListener("jpush.openNotification", function (event) {
        var alertContent;
        if(this.device.platform == "Android") {
          alertContent = event
        } else {
          alertContent = event
        }
        //打开消息列表的页面
        let modal = this.modalCtrl.create('MessageListPage');
        modal.present();
        //alert("open Notification:" + JSON.stringify(alertContent));
      }, false);

      //接收通知监听
      document.addEventListener("jpush.receiveNotification", (event:any) =>{
        var alertContent
        if(this.device.platform == "Android") {
          alertContent = event
        } else {
          alertContent = event
        }
        //进行消息同步
        this.messageService.syncMsg(()=>{
          //更新显示的消息数量
          this.events.publish('updateMsgCount');
        })
        alert("receive Notification:" + JSON.stringify(alertContent))
      }, false)

      //判断系统设置是否开启了推送
      this.jPush.getUserNotificationSettings().then((result) => {
        if(result == 0) {
          // 系统设置中已关闭应用推送。
          this.appService.alert("本机的系统设置未开启推送！请在设置中开启");
        } else if(result > 0) {
          // 系统设置中打开了应用推送。
          //alert("系统设置已开启推送！");
        }
      })
      //调试模式
      //jPush.setDebugMode(true);
      //获取RegistrationID
      // jPush.getRegistrationID()
      //   .then(regId => {
      //     alert(regId)
      //     //this.storage.set('regId', regId);
      //   })
      //   .catch(err => alert(err));

      //设置标签
      // jPush.setTags({ sequence: 1, tags: ['tag1', 'tag2'] }).then((result:any) => {
      //   alert(JSON.stringify(result));
      // }).catch((err:any)=>{
      //   alert(JSON.stringify("setTags err:"+JSON.stringify(err)));
      // })
    } else {//web
      console.warn('Push notifications only work on a real device');
      this.appService.domain = AppConfig.WebApi;;
      AppGlobal.platform = "WEB";
    }


  }

  initAfterLogin() {
    //获取当前登录人的信息
    this.appService.httpPost('AppUserCtrl_getMyInfo',{},null,res => {
      //设置用户数据
      this.setUser(res.datas);
      //消息同步
      this.messageService.syncMsg();
      //机构信息同步
      this.orgService.sysnOrg();
      //console.log(this.userInfoService.user);
      if(this.platform.is('cordova')){//native
        //登录成功后，定时器每分钟执行一次检查极光是否已经注册，若已经注册则绑定alias并且停止定时器
        this.jPushReg();
        //获取用户头像
        this.getProfilePic();
      } else{//web
        this.appService.httpPost("AppUserCtrl_getMyPhoto",{},null,
          (res)=>{
            if(res.datas[0].name == "photoPath"){//服务端存在头像
              let url = AppConfig.ServerDomain + res.datas[0].value;
              this.userInfoService.user.profilePicUri = url;
            }
          },false);
      }
    },true)

  }

  setUser(data){
    this.userInfoService.user.userCode = data[1].data.dlzh.value;
    this.userInfoService.user.password = data[1].data.password.value;
    this.userInfoService.user.userId = data[0].data.cId.value;
    this.userInfoService.user.userName = data[0].data.userName.value;
    this.userInfoService.user.nickName = data[0].data.nickName.value;
    this.userInfoService.user.orgId = data[2].data.orgId.value;
    this.userInfoService.user.orgName = data[2].data.jgmc.value;
    this.userInfoService.user.gender = data[0].data.xb.value;
    this.userInfoService.user.mobileNumber = data[0].data.sjhm.value;
    this.userInfoService.user.birthday = data[0].data.csrq.value;
    this.userInfoService.user.mail = data[0].data.mail.value;
    this.userInfoService.user.areaCode = data[0].data.xzqhDm.value;
  }

  //极光注册服务处理
  jPushReg(){
    var interval = setInterval(() => {
      //获取RegistrationID，判断极光是否注册成功
      this.jPush.getRegistrationID().then(regId => {
        if(regId != ""){//RegistrationID非空，表示注册成功
          AppGlobal.jPushInited = true;
          this.jPush.setAlias({sequence: 1,alias:this.userInfoService.user.userCode}).then((result:any) =>{
            alert("注册别名Alias成功："+JSON.stringify(result));
          },(err:any)=>{
            alert(JSON.stringify("setAlias err:"+err));
          }).catch((err:any) => {
            alert(JSON.stringify("setAlias err:"+err));
          });
          clearInterval(interval);
        } else {
          this.jPush.init();
          alert("尚未初始化，30s后重试");
        }
      },(err:any)=>{
        alert("获取RegistrationID失败："+JSON.stringify(err));
      }).catch(err => alert("获取RegistrationID失败："+JSON.stringify(err)));
    }, 30000);
  }
  //获取头像
  getProfilePic(){
    //先判断头像文件是否存在
    this.file.checkFile(AppGlobal.savePath,AppGlobal.myProfilePicName)
      .then(()=>{
        //文件存在
        let picPath = (AppGlobal.savePath + AppGlobal.myProfilePicName);
        this.userInfoService.user.profilePicUri = AppGlobal.platform=="iOS"?
            picPath.replace(/^file:\/\//, ''):picPath;
      },()=>{
          //文件不存在，从服务器获取头像信息
          this.appService.httpPost("AppUserCtrl_getMyPhoto",{},null,
              (res:ResDataModel)=>{
                  if(res.datas[0].name == "photoPath"){//服务端存在头像
                      //下载保存至本地
                      let url = AppConfig.ServerDomain + res.datas[0].value;
                      let picPath = AppGlobal.savePath + AppGlobal.myProfilePicName;
                      this.userInfoService.user.profilePicUri = url;

                      const fileTransfer: FileTransferObject = this.transfer.create();
                      fileTransfer.download(encodeURI(url), picPath).then((entry) => {
                          //头像下载成功
                          this.userInfoService.user.profilePicUri = AppGlobal.platform=="iOS"?
                              picPath.replace(/^file:\/\//, ''):picPath;
                      }, (error:any) => {
                          console.error(error);
                          //this.loadingService.presentTip('操作提醒', '由于部分手机出现异常,请您进入手机设置-应用管理-Ceshiname-权限，将存储权限打开后再进行升级，由此给您带来的不便，敬请谅解。');
                      }).catch(err=>{
                      });

                  } else {//服务端没有头像，使用默认头像
                      this.userInfoService.user.profilePicUri = "./assets/icon/user.jpg"
                  }
              },false);
      })
      .catch(()=>{
        //文件不存在，从服务器获取头像信息
        this.appService.httpPost("AppUserCtrl_getMyPhoto",{},null,
          (res:ResDataModel)=>{
            if(res.datas[0].name == "photoPath"){//服务端存在头像
              //下载保存至本地
              let url = AppConfig.ServerDomain + res.datas[0].value;
              let savePath = AppGlobal.savePath + AppGlobal.myProfilePicName;
              this.userInfoService.user.profilePicUri = url;

              const fileTransfer: FileTransferObject = this.transfer.create();
              fileTransfer.download(encodeURI(url), savePath).then((entry) => {
                //头像下载成功
                this.userInfoService.user.profilePicUri = savePath;
              }, (error:any) => {
                console.error(error);
                //this.loadingService.presentTip('操作提醒', '由于部分手机出现异常,请您进入手机设置-应用管理-Ceshiname-权限，将存储权限打开后再进行升级，由此给您带来的不便，敬请谅解。');
              }).catch(err=>{
                console.error(err);
              });

            } else {//服务端没有头像，使用默认头像
              this.userInfoService.user.profilePicUri = "./assets/icon/user.jpg"
            }
          },false);
      })

  }
}
